package github.leavesczy.matisse.samples

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView

import java.io.InputStream
import github.leavesczy.matisse.CoilImageEngine
import github.leavesczy.matisse.DefaultMediaFilter
import github.leavesczy.matisse.Matisse
import github.leavesczy.matisse.MatisseCapture
import github.leavesczy.matisse.MatisseCaptureContract
import github.leavesczy.matisse.MatisseContract
import github.leavesczy.matisse.MediaResource
import github.leavesczy.matisse.MediaType
import github.leavesczy.matisse.SmartCaptureStrategy
import github.leavesczy.matisse.FileProviderCaptureStrategy

/**
 * 简单的Matisse调用示例
 * 展示最基本的图片和视频选择功能
 */
class SimpleMatisseActivity : AppCompatActivity() {

    private lateinit var mediaRecyclerView: RecyclerView
    private lateinit var mediaAdapter: SimpleMediaAdapter
    private val mediaList = mutableListOf<MediaResource>()

    private val takePictureLauncher = registerForActivityResult(
        MatisseCaptureContract()
    ) { result ->
        if (result != null) {
            mediaList.clear()
            mediaList.add(result)
            mediaAdapter.notifyDataSetChanged()
            updateResultText()
        }
    }

    private val mediaPickerLauncher = registerForActivityResult(
        MatisseContract()
    ) { result ->
        if (!result.isNullOrEmpty()) {
            mediaList.clear()
            mediaList.addAll(result)
            mediaAdapter.notifyDataSetChanged()
            updateResultText()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_simple_matisse)

        initViews()
        setupRecyclerView()
    }

    private fun initViews() {
        mediaRecyclerView = findViewById(R.id.mediaRecyclerView)

        // 图片选择
        findViewById<Button>(R.id.btnSelectImages).setOnClickListener {
            selectImages()
        }

        // 视频选择
        findViewById<Button>(R.id.btnSelectVideos).setOnClickListener {
            selectVideos()
        }

        // 图片和视频
        findViewById<Button>(R.id.btnSelectImagesAndVideos).setOnClickListener {
            selectImagesAndVideos()
        }

        // 拍照
        findViewById<Button>(R.id.btnTakePicture).setOnClickListener {
            takePicture()
        }

        updateResultText()
    }

    private fun setupRecyclerView() {
        mediaAdapter = SimpleMediaAdapter(mediaList)
        mediaRecyclerView.layoutManager = GridLayoutManager(this, 2)
        mediaRecyclerView.adapter = mediaAdapter
    }

    private fun selectImages() {
        val matisse = Matisse(
            gridColumns = 3,
            maxSelectable = 9,
            fastSelect = false,
            mediaType = MediaType.ImageOnly,
            mediaFilter = DefaultMediaFilter(),
            imageEngine = CoilImageEngine(),
            singleMediaType = true,
            captureStrategy = getCaptureStrategy()
        )
        mediaPickerLauncher.launch(matisse)
    }

    private fun selectVideos() {
        val matisse = Matisse(
            gridColumns = 3,
            maxSelectable = 5,
            fastSelect = false,
            mediaType = MediaType.VideoOnly,
            mediaFilter = DefaultMediaFilter(),
            imageEngine = CoilImageEngine(),
            singleMediaType = true,
            captureStrategy = null // 视频不支持拍照
        )
        mediaPickerLauncher.launch(matisse)
    }

    private fun selectImagesAndVideos() {
        val matisse = Matisse(
            gridColumns = 3,
            maxSelectable = 9,
            fastSelect = false,
            mediaType = MediaType.ImageAndVideo,
            mediaFilter = DefaultMediaFilter(),
            imageEngine = CoilImageEngine(),
            singleMediaType = false,
            captureStrategy = getCaptureStrategy()
        )
        mediaPickerLauncher.launch(matisse)
    }

    private fun takePicture() {
        val matisseCapture = MatisseCapture(captureStrategy = getCaptureStrategy())
        takePictureLauncher.launch(matisseCapture)
    }

    private fun getCaptureStrategy() = SmartCaptureStrategy(
        fileProviderCaptureStrategy = FileProviderCaptureStrategy(
            authority = "github.leavesczy.matisse.samples.FileProvider"
        )
    )

    private fun updateResultText() {
        findViewById<TextView>(R.id.tvResult).text = 
            "已选择 ${mediaList.size} 个文件"
    }

    private class SimpleMediaAdapter(private val mediaList: List<MediaResource>) : 
        RecyclerView.Adapter<SimpleMediaAdapter.MediaViewHolder>() {

        class MediaViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val imageView: android.widget.ImageView = itemView.findViewById(R.id.mediaImageView)
            val textView: TextView = itemView.findViewById(R.id.mediaTextView)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MediaViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.item_media, parent, false)
            return MediaViewHolder(view)
        }

        override fun onBindViewHolder(holder: MediaViewHolder, position: Int) {
            val mediaResource = mediaList[position]
            
            // 使用传统方式加载图片
            try {
                val inputStream: InputStream? = holder.itemView.context.contentResolver.openInputStream(mediaResource.uri)
                val bitmap = BitmapFactory.decodeStream(inputStream)
                holder.imageView.setImageBitmap(bitmap)
                inputStream?.close()
            } catch (e: Exception) {
                // 如果加载失败，显示默认背景
                holder.imageView.setImageResource(android.R.drawable.ic_menu_gallery)
            }

            holder.textView.text = "${mediaResource.mimeType}\n${mediaResource.path}"
        }

        override fun getItemCount(): Int = mediaList.size
    }
} 